from pydantic import BaseModel
import uvicorn
from typing import Optional
import threading
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import plotly.graph_objects as go
from tiingo import TiingoClient
from sklearn.preprocessing import RobustScaler, PowerTransformer, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Bidirectional, LSTM, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.losses import Huber
from sklearn.metrics import mean_absolute_error, mean_squared_error
from flask import Flask, request, jsonify
from data_pipeline import DataPipeline
from model import ForecastingSystem
import os  # 添加os模块导入

app = Flask(__name__)

@app.route('/', methods=['GET'])
def home():
    api_key = "2fedfd72fe32b769868235e798fc3e8831cf79c1"  # 手动输入你的 Tiingo API 密钥
    data_pipeline = DataPipeline(api_key=api_key)
    system = ForecastingSystem(data_pipeline=data_pipeline)
    df = system.data_pipeline.get_processed_data().head(10)
    html_table = df.to_html(classes='data', header="true", table_id="table_id")
    return f"""
    <html>
        <head>
            <title>Stock Data</title>
            <style>
                .data {{
                    width: 100%;
                    border-collapse: collapse;
                }}
                .data th, .data td {{
                    border: 1px solid #ddd;
                    padding: 8px;
                }}
                .data th {{
                    background-color: #f2f2f2;
                    text-align: left;
                }}
            </style>
        </head>
        <body>
            <h1>Stock Data</h1>
            {html_table}
        </body>
    </html>
    """


@app.route('/data', methods=['GET'])
def data():
    system = ForecastingSystem()
    df = system.data_pipeline.get_processed_data()
    return jsonify(df.head(10).to_dict(orient='records'))

@app.route('/forecast', methods=['POST'])
def forecast():
    try:
        data = request.json
        system = ForecastingSystem()
        (X_train, y_train), (X_val, y_val), (X_test, y_test) = system.prepare_data_from_request(data)
        history = system.train_model(X_train, y_train, X_val, y_val)
        forecast = system.forecast()
        return jsonify(forecast.tolist())
    except Exception as e:
        return jsonify({"error": str(e)}), 500

if __name__ == "__main__":
    # 确保Flask应用监听正确的端口
    app.run(host='0.0.0.0', port=5000, debug=True)